package com.alogic.idnote;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import com.alogic.load.Loadable;
import com.anysoft.util.Configurable;
import com.anysoft.util.JsonTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Reportable;
import com.anysoft.util.XMLConfigurable;
import com.anysoft.util.XmlElementProperties;
import com.anysoft.util.XmlTools;

/**
 * IdNote
 * @author yyduan
 * @since 1.6.12.13 [20181213 duanyy] <br>
 */
public interface IdNote extends Loadable,Reportable{
	
	/**
	 * 获取Id的说明信息
	 * @return 说明信息
	 */
	public String getNote();
	
	/**
	 * 获取id的建议信息
	 * @return 建议信息
	 */
	public String getAdvise();
	
	/**
	 * 虚基类
	 * @author yyduan
	 *
	 */
	public abstract static class Abstract implements IdNote,XMLConfigurable,Configurable {
		/**
		 * a logger of slf4j
		 */
		protected static final Logger LOG = LoggerFactory.getLogger(IdNote.class);

		/**
		 * id
		 */
		protected String id;

		/**
		 * 数据加载时间戳
		 */
		protected long timestamp = System.currentTimeMillis();
		
		/**
		 * 数据的生存周期:30分钟
		 */
		public static final long TTL = 30 * 60 * 1000L;	
				
		@Override
		public String getId() {
			return id;
		}

		@Override
		public long getTimestamp() {
			return timestamp;
		}
		
		@Override
		public boolean isExpired() {
			return System.currentTimeMillis() - timestamp > TTL;
		}
	
		@Override
		public void expire(){
			timestamp = timestamp - TTL;
		}

		@Override
		public void report(Element xml) {
			if (xml != null){
				XmlTools.setString(xml, "module", getClass().getName());
				XmlTools.setString(xml,"id",getId());
			}
		}

		@Override
		public void report(Map<String, Object> json) {
			if (json != null){
				JsonTools.setString(json,"module",getClass().getName());
				JsonTools.setString(json,"id",getId());
			}
		}

		@Override
		public void configure(Properties p) {
			id = PropertiesConstants.getString(p,"id",id);
		}

		@Override
		public void configure(Element e, Properties p) {
			XmlElementProperties props = new XmlElementProperties(e,p);
			configure(props);
		}
	}
	
	/**
	 * 缺省实现
	 * @author yyduan
	 *
	 */
	public static class Default extends Abstract{
		protected String note;
		protected String advise;
		
		@Override
		public void configure(Properties p) {
			super.configure(p);
			note = PropertiesConstants.getString(p, "note", "");
			advise = PropertiesConstants.getString(p, "advise", "");
		}
		
		@Override
		public String getNote() {
			return note;
		}
		
		@Override
		public String getAdvise() {
			return advise;
		}
	}
}
